<?php
class CsvController extends AppController {

	public $name = 'csv';
	function beforeFilter() {
	    parent::beforeFilter(); 
		$this->C_auth->autoRedirect = false; //For override login
	    $this->C_auth->allowedActions = array('csvexport','docsvexport','csvimport','docsvimport');

	}	

	public function csvimport() {
        $this->_teamRights();	
		$shop_id = $this->my->id;	
		$this->set('shop_id',$shop_id);		
	}
	
	public function docsvimport() {
	    $shop_id = intval(Request::get_args('shop_id'));	
		$query = array(
				'fields' => array('shopinfo.*'),
				'conditions' => array('shopinfo.id' => $this->my->id),
				);	
	    $row = POP::exe('[@@:UM shopinfo][@@:QU find:all]',$query);	


		
	    $row= $row['shopinfo'];
	    $goods_num=$row['goods_num'];
	    //取得上传的csv文件
	    $res = fopen($_FILES['filename']['tmp_name'],"r");
	    while ($arr2 = fgetcsv($res,50000)) {
		    $arr[]=$arr2;
	    }
	    $arrobj = new arrayiconv();
	    if (Request::get_args("chast")=='utf-8') {
		
	    }else{
		    $arr = $arrobj->Conversion($arr,Request::get_args("chast"),"utf-8");
	    }

	    array_shift($arr);//删除第一行

		Loader::import('lib.cupload');	
	    $cupload = new upload();//文件上传处理
	    $errstr="";
	    foreach ($arr as $k=> $value){
		    $str_arr = $value;
		    //下载远程图片到本地
            //print_r($str_arr);
		    $imginfo['img_original']="";
		    $imginfo['img_original']=GrabImage(end($str_arr));
		    if (empty($imginfo['img_original'])||!isset($imginfo['img_original'])) {
			    $imginfo['img_original']='skin/images/nopic_big.gif';
		    }
			    $rootpath = trim(str_replace(Param::read('wwwrootPatch'),"",Param::read('htdocPatch')),'/') ;
                $rootpath = !empty($rootpath)?	('/'.$rootpath) : '';			
		    //取得后缀名
		    $ext = strtolower(strrchr($imginfo['img_original'],'.'));
		    $new_filename = date("Ymdhis").mt_rand(10,99).$ext;
		    $goods_thumb = $rootpath. Param::read('upfiles.path') ."/goods/".date("Y")."/".date("m")."/".date("d")."/thumb_".$new_filename;
		    $goods_img = $rootpath . Param::read('upfiles.path') ."/goods/".date("Y")."/".date("m")."/".date("d")."/".$new_filename;

			$rootdir = trim(Param::read('wwwrootPatch'),'/');
		    //生成图片
		    $cupload->create_thumb($rootdir . $imginfo['img_original'], $rootdir . $goods_thumb,300,300);
		    $cupload->create_thumb($rootdir . $imginfo['img_original'], $rootdir . $goods_img,300,300);
		    $info['shop_id']=$shop_id;
		    $info['goods_name']=$str_arr[2];
		    $info['cat_id']=$str_arr[3];
		    $info['ucat_id']=$str_arr[4];
		    $info['brand_id']=$str_arr[5];
		    $info['type_id']=$str_arr[6];
		    $info['goods_intro']=$str_arr[7];
		    $info['goods_wholesale']=$str_arr[8];
		    $info['goods_number']=$str_arr[9];
		    $info['goods_price']=$str_arr[10];
		    $info['transport_price']=$str_arr[11];
		    $info['keyword']=str_ireplace("-",",",$str_arr[12]);
		    $info['is_delete']=$str_arr[13];
		    $info['is_best']=$str_arr[14];
		    $info['is_new']=$str_arr[15];
		    $info['is_hot']=$str_arr[16];
		    $info['is_promote']=$str_arr[17];
		    $info['is_on_sale']=$str_arr[18];
		    $info['is_set_image']=$str_arr[19];
		    $info['goods_thumb']=$goods_thumb;
		    $info['pv']=$str_arr[21];
		    $info['favpv']=$str_arr[22];
		    $info['sort_order']=$str_arr[23];
		    $info['add_time']=!empty($str_arr[24])?$str_arr[24]:date("Y-m-d H:i:s");
		    $info['last_update_time']=!empty($str_arr[25])?$str_arr[25]:date("Y-m-d H:i:s");
		    $info['lock_flg']=$str_arr[26];	
		    $post =array();
		    $post['goods'] = $info;
			$goods_id = POP::exe('[@@:UM goods][@@:QU save]',$post);						
		    $imginfo['goods_id']=$goods_id;
		    $imginfo['thumb_url']=$goods_thumb;
		    $imginfo['img_url']=$goods_img;
		    $post =array();
		    $post['goodsgallery'] = $imginfo;
			$img_id = POP::exe('[@@:UM goodsgallery][@@:QU save]',$post);	
		    if ($goods_id==0||$img_id==0) {
			    $errstr.= ($k+1).",";
		    }		
		    $goods_num=$goods_num+1;
			
			$query  = array();		
			$query['keyid'] = true;
			$safeData['shopinfo'] = array('goods_num'=>$goods_num);				
			$query['set'] = $safeData;	
			$query['conditions'] = array('shopinfo.id'=>$shop_id);		
			POP::exe('[@@:UM shopinfo][@@:QU save]',$query);			
	    }
	    $errstr= substr($errstr,0,-1);
	    if (empty($errstr)) {
		    $this->flash('导入成功！', Router::url('goods/ulist'));
	    }else{
		    $this->flash("第".$errstr."行导入失败", Router::url('goods/ulist'));
	    }	
	}	
	
	public function csvexport() {
        $this->_teamRights();	
		$shop_id = $this->my->id;

		$query = array(
				'fields' => array('goods.*'),
				'conditions' => array('goods.shop_id' => $shop_id),
				'order'=>' id DESC '
				);	
	    $goods_list = POP::exe('[@@:UM goods][@@:QU find:all]',$query);	

		$this->set('goods_list',$goods_list);
		$this->set('shop_id',$shop_id);		
	}	

	public function docsvexport() {
	    $shop_id = intval(Request::get_args('shop_id'));
	    //取得商品列表
	    $goods_ids = Request::get_args("goods_id");	
	    $goods_id_str = "";
	    foreach ($goods_ids as $value){
		    $goods_id_str.="$value,";
	    }
	    $chast = Request::get_args("chast");
	    $file_name = Request::get_args("filename");
	    if (empty($file_name)) {
		    $file_name=date("YmdHis");
	    }
	    $file_name .=".csv";
	    $file_name =iconv("gbk",$chast,$file_name);
	    $goods_id_str = substr($goods_id_str,0,-1);

		$query = array(
				'joins' => array(
				array('type'=>'left','table'=>'goodsgallery','conditions'=>array('goodsgallery.goods_id' =>'goods.id')),					
				),
				'fields' => array('goods.*','goodsgallery.goods_id','goodsgallery.img_original'),
				'conditions' => array('goods.id' =>$goods_id_str),
				'group' => ' goods.id DESC '
			);	
	    $goods_list = POP::exe('[@@:UM goods][@@:QU find:all]',$query);			
	    header( "Cache-Control: public" );
        header( "Pragma: public" );
	    header("Content-type:application/vnd.ms-excel");
        header("Content-Disposition:attachment;filename=".$file_name);
        header('Content-Type:APPLICATION/OCTET-STREAM');
	    ob_start();
	    $header_str = iconv("gbk",$chast,"商品ID,店铺ID,商品名称,分类ID,自定义分类ID,品牌ID,属性类型ID,商品描述,批发说明,商品库存,商品价格,商品运费,关键字,是否删除,是否精品,是否新品,是否热销,是否特价,是否上架,是否设置图片,商品缩略图,关注度,被收藏次数,排序,添加时间,最后更新时间,是否锁定,原始图片 \n");
		
	    $file_str="";
	    foreach ($goods_list as $value){
		    $value = $value['g'] + $value['i'];			
		    $goods_name_pos = strpos($value['goods_name'],",");//商品名称
		    $goods_price_pos = strpos($value['goods_price'],",");//商品价格
		    $goods_intro_pos = strpos($value['goods_intro'],",");//商品说明
		    $goods_goods_wholesale_pos = strpos($value['goods_wholesale'],",");//批发说明
		    $goods_transport_price_pos = strpos($value['transport_price'],",");//运费
		    $goods_keyword_pos = strpos($value['keyword'],",");//关键词
		    $goods_thumb_pos = strpos($value['goods_thumb'],",");//缩略图
		    $goods_img_original_pos = strpos(Request::getHostInfo().$value['img_original'],",");//原始图
		    $value['goods_name']=str_replace("/r","","{$value['goods_name']}");
		    $value['goods_name']=str_replace('"','""',"{$value['goods_name']}");
		    $value['goods_name']=str_replace("/n","","{$value['goods_name']}");
		    $value['goods_price']=str_replace("/r","","{$value['goods_price']}");
		    $value['goods_price']=str_replace("/n","","{$value['goods_price']}");
      //	$value['goods_price']=str_replace('"','""',"{$value['goods_price']}");
		    $value['goods_intro']=str_replace("/r","","{$value['goods_intro']}");
		    $value['goods_intro']=str_replace("<br>","&lt;br&gt;","{$value['goods_intro']}");
		    $value['goods_intro']=str_replace("<br/>","&lt;br/&gt;","{$value['goods_intro']}");
		    $value['goods_intro']=str_replace("/n","","{$value['goods_intro']}");
		    $value['goods_intro']=str_replace("/t","","{$value['goods_intro']}");
		    $value['goods_intro']=str_replace('"','""',"{$value['goods_intro']}");
		 // $value['goods_intro']="\"".$value['goods_intro']."\"";
		    $value['goods_wholesale']=str_replace("/r","","{$value['goods_wholesale']}");
		    $value['goods_wholesale']=str_replace("/n","","{$value['goods_wholesale']}");
		    $value['goods_wholesale']=str_replace('"','""',"{$value['goods_wholesale']}");
		    $value['googoods_wholesales_name']=str_replace("/n","","{$value['goods_wholesale']}");
		    $value['googoods_wholesales_name']=str_replace("/r","","{$value['goods_wholesale']}");
		    $value['googoods_wholesales_name']=str_replace('"','""',"{$value['goods_wholesale']}");
		    $value['transport_price']=str_replace("/r","","{$value['transport_price']}");
		    $value['transport_price']=str_replace("/n","","{$value['transport_price']}");
		    $value['transport_price']=str_replace('"','""',"{$value['transport_price']}");
		    $value['keyword']=str_replace("/r","","{$value['keyword']}");
		    $value['keyword']=str_replace('"','""',"{$value['keyword']}");
		    $value['keyword']=str_replace("/n","","{$value['keyword']}");
		    $value['keyword']=str_replace(",","-","{$value['keyword']}");
	        if ($goods_name_pos === false) {
			    $goods_name = iconv("utf-8",$chast,$value['goods_name']);
	        }else{
	    	    $goods_name ="\"".iconv("utf-8",$chast,$value['goods_name'])."\"";
	        }//商品名称
	        if ($goods_price_pos === false) {
			
	        }else{
	    	    $value['goods_price'] ="\"".iconv("utf-8",$chast,$value['goods_price'])."\"";
	        }//商品价格
	        if ($goods_intro_pos === false) {
			    $value['goods_intro']='"'.iconv("utf-8",$chast,$value['goods_intro']).'"';
	        }else{
	    	    $value['goods_intro'] ='"'.iconv("utf-8",$chast,$value['goods_intro']).'"';
	        }//商品说明
	        if ($goods_goods_wholesale_pos === false) {
			
	        }else{
	    	    $value['goods_wholesale'] ="\"".iconv("utf-8",$chast,$value['goods_wholesale'])."\"";
	        }//批发说明
	        if ($goods_keyword_pos === false) {
			
	        }else{
	    	    $value['goods_price'] ="\"".iconv("utf-8",$chast,$value['goods_price'])."\"";
	        }//关键词
	        if ($goods_thumb_pos === false) {
			
	        }else{
	    	    $value['goods_thumb'] ="\"".iconv("utf-8",$chast,$value['goods_thumb'])."\"";
	        }//缩略图
	        if ($goods_img_original_pos === false) {
			
	        }else{
	    	    $value['img_original'] ="\"".iconv("utf-8",$chast,$value['img_original'])."\"";
	        }
		    $file_str .=$value['id'].",".$value['shop_id'].",".$goods_name.",".$value['cat_id'].",".$value['ucat_id'].",".$value['brand_id'].",".$value['type_id'].",".$value['goods_intro'].",".iconv("utf-8",$chast,$value['goods_wholesale']).".,".$value['goods_number'].",".$value['goods_price'].",".$value['transport_price'].",".iconv("utf-8",$chast,$value['keyword']).",".$value['is_delete'].",".$value['is_best'].",".$value['is_new'].",".$value['is_hot'].",".$value['is_promote'].",".$value['is_on_sale'].",".$value['is_set_image'].",".$value['goods_thumb'].",".$value['pv'].",".$value['favpv'].",".$value['sort_order'].",".$value['add_time'].",".$value['last_update_time'].",".$value['lock_flg'].",".Request::getHostInfo().$value['img_original']."\n";
	    }
	    ob_end_clean();
	    echo $header_str;
	    echo $file_str;	
        exit;		
	}	
}

function GrabImage($url,$filename="") {  
	if($url==""){
		return false;
		exit;
	}
	if($filename=="") { 
		$typearr=array("jpg","gif","png");
		$ext = strtolower(substr(strrchr($url,'.'),1,10));
		if(!in_array($ext,$typearr)){
			//echo "文件类型不对";
			return false;
		}
		$filename=md5(uniqid(mt_rand(), true)).substr(microtime(),2,8).".".$ext; 
	} 

	ob_start(); 
	if(@readfile($url)){
		$img = ob_get_contents(); 
	}else{
		//echo "无法下载文件";
		return false;
		exit;
	}
	ob_end_clean(); 
	$size = strlen($img);

	if ($size<1) {
		return false;
		exit();
	}	
	$rootpath = trim(str_replace(Param::read('wwwrootPatch'),"",Param::read('htdocPatch')),'/') ;

    $rootpath = !empty($rootpath)?	('/'.$rootpath) : '';	
				
	$dir = $rootpath . Param::read('upfiles.path') . "/goods_temp/".date("Y")."/".date("m")."/".date("d")."/";

	$rootdir = trim(Param::read('wwwrootPatch'),'/') . $dir;
	mkdirs($rootdir);
	if (!is_dir($rootdir)) {
		$i = 0;
		echo $rootdir;
		exit;
		while (!@mkdir($rootdir, 0776)) {
		 if (is_dir($rootdir)) break;
		 $i ++; 
		 if (mkdir($rootdir . str_repeat("/..", $i), 0776));
		 $i = 0;
		}
	}
	$fp2=fopen($rootdir.$filename, "a"); 
	if ($fp2) {
		fwrite($fp2,$img); 
		fclose($fp2); 
	}else{
		
	}
	$img_dir = $dir.$filename;
	return $img_dir; 
}

function mkdirs($dir)  
{  
	if(!is_dir($dir))  
	{   if(!mkdirs(dirname($dir)))
	    {  
	    	return false; 
	    }  
		if(!mkdir($dir,0776))
		{  
		    return false; 
		} 
	}  
	return true; 
} 

class arrayiconv    
{    
	static protected $in;    
	static protected $out;    
	/**   
	  * 静态方法,该方法输入数组并返回数组   
	  *   
	  * @param unknown_type $array 输入的数组   
	  * @param unknown_type $in 输入数组的编码   
	  * @param unknown_type $out 返回数组的编码   
	  * @return unknown 返回的数组   
	  */   
	static public function Conversion($array,$in,$out)    
	{    
	  self::$in=$in;    
	  self::$out=$out;    
	  return self::arraymyicov($array);    
	}    
	/**   
	  * 内部方法,循环数组   
	  *   
	  * @param unknown_type $array   
	  * @return unknown   
	  */   
	static private function arraymyicov($array)    
	{    
	  foreach ($array as $key=>$value)    
	  {    
	   $key=self::myiconv($key);    
	   if (!is_array($value)) {    
		$value=self::myiconv($value);    
	   }else {    
		$value=self::arraymyicov($value);    
	   }    
	   $temparray[$key]=$value;    
	  }    
	  return $temparray;    
	}    
	/**   
	  * 替换数组编码   
	  *   
	  * @param unknown_type $str   
	  * @return unknown   
	  */   
	static private function myiconv($str)    
	{    
	  return iconv(self::$in,self::$out,$str);    
	}    
}

?>